package com.malbbmsomanager.print;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import com.malbbmsomanager.transactions.DM_BBM_InvoiceSalesOrder;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;

public class DM_BBM_Receipt_PrintPreview extends Activity implements
		ActionBar.OnNavigationListener {

	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	private String DBNAME = "dminvoicemanagerbbm.db";
	private SQLiteDatabase mydb;
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	String PrintRefNumber, CurrentRepCode, ReceiptPayType, ReceiptDebtorCode;
	LinearLayout cashreceiptdisplay, chequereceiptdisplay;
	LinearLayout chqaddress1, chqaddress2, chqaddress3;
	RelativeLayout cashsumaryheading, checksumaryheading;
	// Cash Details Print
	EditText cash_print_value_a, cash_print_value_b, cash_print_value_c,
			cash_print_value_d, cash_print_value_e, cash_print_value_f,
			cash_print_value_g, cash_print_value_h, cash_print_value_i,
			cash_print_value_j;
	EditText amountinwordsprint, etdisplaytotalvalue, cheque_print_value_a,
			cheque_print_value_b, cheque_print_value_c, cheque_print_value_d,
			cheque_print_value_e, cheque_print_value_f, cheque_print_value_g,
			cheque_print_value_h, cheque_print_value_i, cheque_print_value_j,
			cheque_print_value_k, cheque_print_value_l, cheque_print_value_m;
	EditText cheque_print_value_p, cheque_print_value_q, cheque_print_value_r,
			cheque_print_value_s, cheque_print_value_t;
	BigDecimal AmountTotalValue = new BigDecimal("0.00");
	// action bar
	private ActionBar actionBar;
	SimpleDateFormat originalFormat = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy");
	Date settingDate;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_receipt_printpreview);

		actionBar = getActionBar();

		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		etdisplaytotalvalue = (EditText) findViewById(R.id.etdisplaytotalvalue);
		// Cash Receipt Details Print
		cash_print_value_a = (EditText) findViewById(R.id.cash_print_value_a);
		cash_print_value_b = (EditText) findViewById(R.id.cash_print_value_b);
		cash_print_value_c = (EditText) findViewById(R.id.cash_print_value_c);
		cash_print_value_d = (EditText) findViewById(R.id.cash_print_value_d);
		cash_print_value_e = (EditText) findViewById(R.id.cash_print_value_e);
		cash_print_value_f = (EditText) findViewById(R.id.cash_print_value_f);
		cash_print_value_g = (EditText) findViewById(R.id.cash_print_value_g);
		cash_print_value_h = (EditText) findViewById(R.id.cash_print_value_h);
		cash_print_value_i = (EditText) findViewById(R.id.cash_print_value_i);
		cash_print_value_j = (EditText) findViewById(R.id.cash_print_value_j);

		cheque_print_value_a = (EditText) findViewById(R.id.cheque_print_value_a);
		cheque_print_value_b = (EditText) findViewById(R.id.cheque_print_value_b);
		cheque_print_value_c = (EditText) findViewById(R.id.cheque_print_value_c);
		cheque_print_value_d = (EditText) findViewById(R.id.cheque_print_value_d);
		cheque_print_value_j = (EditText) findViewById(R.id.cheque_print_value_j);
		cheque_print_value_k = (EditText) findViewById(R.id.cheque_print_value_k);
		cheque_print_value_l = (EditText) findViewById(R.id.cheque_print_value_l);
		cheque_print_value_m = (EditText) findViewById(R.id.cheque_print_value_m);

		cheque_print_value_p = (EditText) findViewById(R.id.cheque_print_value_p);
		cheque_print_value_q = (EditText) findViewById(R.id.cheque_print_value_q);
		cheque_print_value_r = (EditText) findViewById(R.id.cheque_print_value_r);
		cheque_print_value_s = (EditText) findViewById(R.id.cheque_print_value_s);
		cheque_print_value_t = (EditText) findViewById(R.id.cheque_print_value_t);

		amountinwordsprint = (EditText) findViewById(R.id.amountinwordsprint);

		cashreceiptdisplay = (LinearLayout) findViewById(R.id.cashreceiptdisplay);
		chequereceiptdisplay = (LinearLayout) findViewById(R.id.chequereceiptdisplay);
		cashsumaryheading = (RelativeLayout) findViewById(R.id.cashsumaryheading);
		checksumaryheading = (RelativeLayout) findViewById(R.id.checksumaryheading);

		chqaddress1 = (LinearLayout) findViewById(R.id.chqaddress1);
		chqaddress2 = (LinearLayout) findViewById(R.id.chqaddress2);
		chqaddress3 = (LinearLayout) findViewById(R.id.chqaddress3);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			PrintRefNumber = extras.getString("TAGID");
		}
		displayPrintPreviewHeader();
		displayPrintPreviewDetails();

	}

	private void displayPrintPreviewHeader() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewHeaderDetails = null;
		String queryViewHeaderDetails;

		try {
			queryViewHeaderDetails = "SELECT * FROM FPRecHed Where RefNo = '"
					+ PrintRefNumber + "'";
			curViewHeaderDetails = mydb.rawQuery(queryViewHeaderDetails, null);
		} catch (Exception e) {

		}

		if (curViewHeaderDetails != null) {
			if (curViewHeaderDetails.getCount() > 0) {
				while (curViewHeaderDetails.moveToNext()) {

					ReceiptPayType = curViewHeaderDetails.getString(21);

					String RefNo = curViewHeaderDetails.getString(1);
					Log.v(TAG, "PAY RefNo**** :" + RefNo);
					String ManuRef = curViewHeaderDetails.getString(2);
					String TxnDate = curViewHeaderDetails.getString(8);
					String Chqno = curViewHeaderDetails.getString(6);
					String ChqDate = curViewHeaderDetails.getString(7);
					ReceiptDebtorCode = curViewHeaderDetails.getString(11);
					String Remarks = curViewHeaderDetails.getString(24);
					String CACHAcNo = curViewHeaderDetails.getString(36);
					String CACHAcBank = curViewHeaderDetails.getString(37);
					String CusBankName = curViewHeaderDetails.getString(39);
					Log.v(TAG, "PAY TYPE**** :" + ReceiptPayType);
					if (ReceiptPayType.trim().equals("CA")) {
						cashreceiptdisplay.setVisibility(LinearLayout.VISIBLE);
						cashsumaryheading.setVisibility(RelativeLayout.VISIBLE);
						chequereceiptdisplay.setVisibility(LinearLayout.GONE);
						checksumaryheading.setVisibility(LinearLayout.GONE);

						Log.v(TAG, "CASH PREVIEW");

						cash_print_value_a.setText(" :" + RefNo);
						cash_print_value_b.setText(" :" + TxnDate);
						cash_print_value_h.setText(" :" + CACHAcNo + "  :"
								+ CACHAcBank);
						cash_print_value_i.setText(" :" + Remarks);
						cash_print_value_j.setText(" :" + "");
						displayDebtorDetails();
					} else {

						Log.v(TAG, "CHEQUE PREVIEW");
						cashreceiptdisplay.setVisibility(LinearLayout.GONE);
						cashsumaryheading.setVisibility(RelativeLayout.GONE);
						chequereceiptdisplay
								.setVisibility(LinearLayout.VISIBLE);
						checksumaryheading.setVisibility(LinearLayout.VISIBLE);

						cheque_print_value_a.setText(" :" + RefNo);
						cheque_print_value_k.setText(" :" + ChqDate);
						cheque_print_value_b.setText(" :" + CusBankName);
						cheque_print_value_l.setText(" :" + ChqDate);
						cheque_print_value_c.setText(" :" + CACHAcNo + " :"
								+ CACHAcBank);
						cheque_print_value_d.setText(" :" + Chqno);
						cheque_print_value_m.setText(" :" + ManuRef);
						cheque_print_value_j.setText(" :" + Remarks);
						displayDebtorDetails();
					}

					/*
					 * BigDecimal StrHedNetTotalVal = new
					 * BigDecimal(StrHedNetTotal.replaceAll("[,]", ""));
					 * BigDecimal StrTotalTaxVal = new
					 * BigDecimal(StrTotalTax.replaceAll("[,]", "")); BigDecimal
					 * PrintSubTotVal =
					 * StrHedNetTotalVal.subtract(StrTotalTaxVal);
					 * PrintSubTotVal = PrintSubTotVal.setScale(2,
					 * BigDecimal.ROUND_HALF_DOWN);
					 */

				}
			} else {
				Log.v(TAG, "NO ITEMS");
			}
		}
		curViewHeaderDetails.close();
		mydb.close();

	}

	private void displayDebtorDetails() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewDebtorDetails = null;
		String queryViewRepDetails;
		Log.v(TAG, "displayDebtorDetails");
		try {
			queryViewRepDetails = "SELECT * FROM fDebtor Where DebCode ='"
					+ ReceiptDebtorCode.trim() + "'";
			curViewDebtorDetails = mydb.rawQuery(queryViewRepDetails, null);
		} catch (Exception e) {

		}
		if (curViewDebtorDetails != null) {
			if (curViewDebtorDetails.getCount() > 0) {
				while (curViewDebtorDetails.moveToNext()) {
					String DebCode = curViewDebtorDetails.getString(1);
					String DebName = curViewDebtorDetails.getString(2);
					String DebAdd1 = curViewDebtorDetails.getString(3);
					String DebAdd2 = curViewDebtorDetails.getString(4);
					String DebAdd3 = curViewDebtorDetails.getString(5);
					Log.v(TAG, "DebCode :" + DebCode);
					Log.v(TAG, "DebName :" + DebName);
					Log.v(TAG, "DebAdd1 :" + DebAdd1);
					Log.v(TAG, "DebAdd2 :" + DebAdd2);
					Log.v(TAG, "DebAdd3 :" + DebAdd3);
					if (ReceiptPayType.trim().equals("CA")) {
						cash_print_value_c.setText(" :" + DebCode);
						cash_print_value_d.setText(" :" + DebName);
						if (DebAdd1.trim().length() == 0) {
							//cash_print_value_e.setVisibility(EditText.GONE);
							cash_print_value_e.setText(" :" + DebAdd1);
						} else {
							cash_print_value_e.setText(" :" + DebAdd1);
						}
						if (DebAdd2.trim().length() == 0) {
							//cash_print_value_f.setVisibility(EditText.GONE);
							cash_print_value_f.setText(" :" + DebAdd2);
						} else {
							cash_print_value_f.setText(" :" + DebAdd2);
						}
						if (DebAdd3.trim().length() == 0) {
							cash_print_value_g.setText(" :" + DebAdd3);
							//cash_print_value_g.setVisibility(EditText.GONE);
						} else {
							cash_print_value_g.setText(" :" + DebAdd3);
						}
					} else {
						cheque_print_value_p.setText(" :" + DebCode);
						cheque_print_value_q.setText(" :" + DebName);
						if (DebAdd1.trim().length() == 0) {
							cheque_print_value_r.setText(" :" + DebAdd1);
							//chqaddress1.setVisibility(LinearLayout.GONE);
						} else {
							cheque_print_value_r.setText(" :" + DebAdd1);
						}
						if (DebAdd2.trim().length() == 0) {
							//chqaddress2.setVisibility(LinearLayout.GONE);
							cheque_print_value_s.setText(" :" + DebAdd2);
						} else {
							cheque_print_value_s.setText(" :" + DebAdd2);
						}
						if (DebAdd3.trim().length() == 0) {
							cheque_print_value_t.setText(" :" + DebAdd3);
							//chqaddress3.setVisibility(LinearLayout.GONE);
						} else {
							cheque_print_value_t.setText(" :" + DebAdd3);
						}

					}
				}
			} else {
				Log.v(TAG, "NOT Found to Debtor Details");
			}
		} else {
			Log.v(TAG, "NOT Found to Debtor Details");
		}
		curViewDebtorDetails.close();
		mydb.close();
	}

	private void displayPrintPreviewDetails() {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		ListView lvtypedes = (ListView) findViewById(R.id.dminvoiceitemsdetlist);
		// create the grid item mapping
		String[] fromtrdes = new String[] { "coldes_1", "coldes_2", "coldes_3" };
		int[] totrdes = new int[] { R.id.grid_title_a, R.id.grid_title_b,
				R.id.grid_title_c };
		// prepare the list of all records
		List<HashMap<String, String>> fillMapstrdes = new ArrayList<HashMap<String, String>>();

		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curViewSODetails = null;
		String queryViewSODetails;

		try {
			queryViewSODetails = "SELECT * FROM FPRecDet Where RefNo = '"
					+ PrintRefNumber + "'";
			curViewSODetails = mydb.rawQuery(queryViewSODetails, null);
		} catch (Exception e) {

		}

		if (curViewSODetails != null) {
			if (curViewSODetails.getCount() > 0) {
				while (curViewSODetails.moveToNext()) {
					String record_0 = curViewSODetails.getString(2);// RefNo1
					String record_1 = curViewSODetails.getString(7);// TxnDate
					String record_2 = curViewSODetails.getString(13);// Amt
					BigDecimal ReceiptTotal = new BigDecimal(
							record_2.replaceAll("[,]", ""));
					AmountTotalValue = AmountTotalValue.add(ReceiptTotal);

					HashMap<String, String> maptrdes = new HashMap<String, String>();
					maptrdes.put("coldes_1", record_0);
					maptrdes.put("coldes_2", record_1);
					maptrdes.put("coldes_3", record_2);
					fillMapstrdes.add(maptrdes);

				}
				// fill in the grid_item layout
				SimpleAdapter adaptertrdes = new SimpleAdapter(this,
						fillMapstrdes, R.layout.dm_bbm_recipt_preview_raw,
						fromtrdes, totrdes);
				lvtypedes.setAdapter(adaptertrdes);
				
				ListAdapter listAdapter = lvtypedes.getAdapter();
				if (listAdapter == null) {
					// pre-condition
					return;
				}

				int totalHeight = 0;
				int desiredWidth = MeasureSpec.makeMeasureSpec(lvtypedes.getWidth(),
						MeasureSpec.AT_MOST);
				for (int i = 0; i < listAdapter.getCount(); i++) {
					View listItem = listAdapter.getView(i, null, lvtypedes);
					listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
					totalHeight += listItem.getMeasuredHeight();
				}

				ViewGroup.LayoutParams params = lvtypedes.getLayoutParams();
				params.height = totalHeight
						+ (lvtypedes.getDividerHeight() * (listAdapter.getCount() - 1));
				lvtypedes.setLayoutParams(params);
				lvtypedes.requestLayout();
				
				
			}
		}
		etdisplaytotalvalue.setText("" + AmountTotalValue);

		try {
			String TotValue = "" + AmountTotalValue;

			double total = Double.parseDouble(TotValue);
			String fortot = String.format("%.2f", total);
			// Log.e("total = 44.50 :", ""+fortot);
			// Log.e("String.valueOf(total) :", String.valueOf(total));
			String[] totsplit = (String.valueOf(fortot)).split("\\.");

			String DesPart = totsplit[0];
			String CentPart = "";
			if (totsplit.length == 2) {
				CentPart = totsplit[1];
			}

			String wordvalue = EnglishNumberToWords.convert(Integer
					.parseInt(DesPart))
					+ ""
					+ ((totsplit.equals("")) ? "" : " Point "
							+ EnglishNumberToWords.convert(Integer
									.parseInt(CentPart)) + " Cents");
			amountinwordsprint.setText(": "+ wordvalue.toUpperCase());
			// Log.e("CentPart :", CentPart);
			/*
			 * int totval = Integer.parseInt(TotValue); NumToWords w = new
			 * NumToWords(); String inwords = w.convert(totval);
			 * amountinwordsprint.setText(inwords);
			 */
		} catch (Exception e) {
			Log.v(TAG, "Exception :" + e);
		}

		curViewSODetails.close();
		mydb.close();
	}

	private String getDeviceTaxnDate() {
		Calendar cad = Calendar.getInstance();
		SimpleDateFormat dfad = new SimpleDateFormat("dd/MM/yyyy");
		String formattedAddDate = dfad.format(cad.getTime());
		return formattedAddDate;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Receipt_PrintPreview.this,
				DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	public static class EnglishNumberToWords {

		private final static String[] tensNames = { "", " ten", " twenty",
				" thirty", " forty", " fifty", " sixty", " seventy", " eighty",
				" ninety" };

		private final static String[] numNames = { "", " one", " two",
				" three", " four", " five", " six", " seven", " eight",
				" nine", " ten", " eleven", " twelve", " thirteen",
				" fourteen", " fifteen", " sixteen", " seventeen", " eighteen",
				" nineteen" };

		private EnglishNumberToWords() {
		}

		private static String convertLessThanOneThousand(int number) {
			String soFar;

			if (number % 100 < 20) {
				soFar = numNames[number % 100];
				number /= 100;
			} else {
				soFar = numNames[number % 10];
				number /= 10;

				soFar = tensNames[number % 10] + soFar;
				number /= 10;
			}
			if (number == 0)
				return soFar;
			return numNames[number] + " hundred" + soFar;
		}

		public static String convert(long number) {
			// 0 to 999 999 999 999
			if (number == 0) {
				return "zero";
			}

			String snumber = Long.toString(number);

			// pad with "0"
			String mask = "000000000000";
			DecimalFormat df = new DecimalFormat(mask);
			snumber = df.format(number);

			// XXXnnnnnnnnn
			int billions = Integer.parseInt(snumber.substring(0, 3));
			// nnnXXXnnnnnn
			int millions = Integer.parseInt(snumber.substring(3, 6));
			// nnnnnnXXXnnn
			int hundredThousands = Integer.parseInt(snumber.substring(6, 9));
			// nnnnnnnnnXXX
			int thousands = Integer.parseInt(snumber.substring(9, 12));

			String tradBillions;
			switch (billions) {
			case 0:
				tradBillions = "";
				break;
			case 1:
				tradBillions = convertLessThanOneThousand(billions)
						+ " billion ";
				break;
			default:
				tradBillions = convertLessThanOneThousand(billions)
						+ " billion ";
			}
			String result = tradBillions;

			String tradMillions;
			switch (millions) {
			case 0:
				tradMillions = "";
				break;
			case 1:
				tradMillions = convertLessThanOneThousand(millions)
						+ " million ";
				break;
			default:
				tradMillions = convertLessThanOneThousand(millions)
						+ " million ";
			}
			result = result + tradMillions;

			String tradHundredThousands;
			switch (hundredThousands) {
			case 0:
				tradHundredThousands = "";
				break;
			case 1:
				tradHundredThousands = "one thousand ";
				break;
			default:
				tradHundredThousands = convertLessThanOneThousand(hundredThousands)
						+ " thousand ";
			}
			result = result + tradHundredThousands;

			String tradThousand;
			tradThousand = convertLessThanOneThousand(thousands);
			result = result + tradThousand;

			// remove extra spaces!
			return result.replaceAll("^\\s+", "").replaceAll("\\b\\s{2,}\\b",
					" ");
		}
	}

	public class NumToWords {
		String string;
		String st1[] = { "", "one", "two", "three", "four", "five", "six",
				"seven", "eight", "nine", };
		String st2[] = { "hundred", "thousand", "lakh", "crore" };
		String st3[] = { "ten", "eleven", "twelve", "thirteen", "fourteen",
				"fifteen", "sixteen", "seventeen", "eighteen", "ninteen", };
		String st4[] = { "twenty", "thirty", "fourty", "fifty", "sixty",
				"seventy", "eighty", "ninety" };

		public String convert(int number) {
			int n = 1;
			int word;
			string = "";
			while (number != 0) {
				switch (n) {
				case 1:
					word = number % 100;
					pass(word);
					if (number > 100 && number % 100 != 0) {
						show("and ");
						// System.out.print("ankit");
					}
					number /= 100;
					break;
				case 2:
					word = number % 10;
					if (word != 0) {
						show(" ");
						show(st2[0]);
						show(" ");
						pass(word);
					}
					number /= 10;
					break;
				case 3:
					word = number % 100;
					if (word != 0) {
						show(" ");
						show(st2[1]);
						show(" ");
						pass(word);
					}
					number /= 100;
					break;
				case 4:
					word = number % 100;
					if (word != 0) {
						show(" ");
						show(st2[2]);
						show(" ");
						pass(word);
					}
					number /= 100;
					break;
				case 5:
					word = number % 100;
					if (word != 0) {
						show(" ");
						show(st2[3]);
						show(" ");
						pass(word);
					}
					number /= 100;
					break;
				}
				n++;
			}
			return string;
		}

		public void pass(int number) {
			int word, q;
			if (number < 10) {
				show(st1[number]);
			}
			if (number > 9 && number < 20) {
				show(st3[number - 10]);
			}
			if (number > 19) {
				word = number % 10;
				if (word == 0) {
					q = number / 10;
					show(st4[q - 2]);
				} else {
					q = number / 10;
					show(st1[word]);
					show(" ");
					show(st4[q - 2]);
				}
			}
		}

		public void show(String s) {
			String st;
			st = string;
			string = s;
			string += st;
		}
	}
}
